import pandas as pd
import os

def query_csv(file_path, encoding='utf-8'):
    """
    读取CSV文件并返回DataFrame
    """
    if not os.path.exists(file_path):
        print(f"File not found: {file_path}")
        return [] 
    try:
        df = pd.read_csv(file_path, encoding=encoding)
        return df
    except Exception as e:
        raise Exception(f"Error reading CSV file: {e}")

def getUsersInfo(path):
    """
    获取用户账户信息
    """
    try:
        users_df = query_csv(path)
        return users_df
    except Exception as e:
        print(f"Error getting users info: {e}")
        return pd.DataFrame(columns=['username', 'password', 'role', 'email', 'account'])

def validateUser(username, password):
    """验证用户登录信息"""
    try:
        users_df = getUsersInfo('data/users.csv')
        user = users_df[(users_df['username'] == username) & (users_df['password'] == password)]
        if not user.empty:  # 正确检查DataFrame是否为空
            return True, {
                "username": user.iloc[0]['username'],  # 使用iloc获取单个元素，而不是Series
                "role": user.iloc[0]['role'],
                "email": user.iloc[0]['email'],
                "account": user.iloc[0]['account']
            }
        return False, None
    except Exception as e:
        print(f"Error validating user: {e}")
        return False, None
